﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

using System.Net.NetworkInformation;
using CWCS.Common;

namespace CWCS.Core.Library.SocketManager
{
    public delegate void DTSNotifyCommandHander(NotifyCommand Command, object state);
    public class DTSSocketClient
    {

        public event DTSNotifyCommandHander Notify;
        private int bytelength = 512;

        private Socket cliSocket;
        private TcpClient tcpSocket;
        private Thread ComThread;
        private bool g_brun;
        private readonly object qLock = new object();
        private int TimeOut = 100;
        StringBuilder strRecvMessage = new StringBuilder();
        public DTSSocketClient(int length)
        {
            g_brun = false;
            bytelength = length;
        }

        public DTSSocketClient()
        {
            g_brun = false;
        }

        public void Close()
        {
            try
            {
                g_brun = false;

                if (ComThread != null)
                {
                    if (ComThread.ThreadState == ThreadState.Running)
                    {
                        ComThread.Abort();
                    }
                    Thread.Sleep(50);
                }

                if (cliSocket != null)
                {
                    if (Connected)
                    {
                        cliSocket.Shutdown(SocketShutdown.Both);
                    }
                    cliSocket.Close();
                }
                GC.Collect();
            }
            catch (SocketException ex)
            {
                RaiseNotifyEvent(NotifyCommand.Break, " 关闭DTS连接异常,异常如下:" + ex.Message);
            }
        }

        public bool Connected
        {
            get
            {
                if (cliSocket != null)
                    return cliSocket.Connected;
                else
                    return false;
            }
        }

        public bool Connect(string strServer, int nPort)
        {
            try
            {

                if (System.String.IsNullOrEmpty(strServer) || nPort == 0)
                { return false; }
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(strServer), nPort);
                cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //cliSocket.Close();
                cliSocket.Connect(iep);
                if (cliSocket != null)
                {
                    RaiseNotifyEvent(NotifyCommand.Connect, "与DTS连接成功！");
                    g_brun = true;
                    ComThread = new Thread(new ThreadStart(Recv));//处理收到的数据
                    ComThread.Start();
                    RaiseNotifyEvent(NotifyCommand.Connect, "等待DTS数据...");
                    return true;
                }
                else
                {
                    RaiseNotifyEvent(NotifyCommand.Break, " 与DTS连接失败！");
                    return false;
                }
            }
            catch (SocketException ex)
            {
                RaiseNotifyEvent(NotifyCommand.Break, " 与DTS连接异常,异常如下:" + ex.Message);
                return false;
            }
        }

        public bool CheckConnect(string strServer, int nPort)
        {
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(strServer), nPort);
            tcpSocket = chenckout.Connect(iep, TimeOut);
            if (tcpSocket != null)
                return true;
            else
                return false;
        }
        //发送数据
        public bool Send(byte[] bytData)
        {
            try
            {
                lock (qLock)
                {
                    if (cliSocket.Connected)
                    {
                        cliSocket.Send(bytData);
                        return true;
                    }
                    else
                    {
                        Close();
                        RaiseNotifyEvent(NotifyCommand.Break, "SendData Fail!");
                        return false;
                    }
                }
            }
            catch (SocketException ex)
            {
                Close();
                RaiseNotifyEvent(NotifyCommand.Break, ex.Message);
                return false;
            }
        }

        //接收数据
        public void Recv()
        {
            byte[] bytBuffer = new byte[bytelength];// 报文长度
            string type = string.Empty;
            while (g_brun)
            {
                try
                {
                    if (cliSocket != null)
                    {
                        if (cliSocket.Connected)
                        {
                            for (int i = 0; i < bytBuffer.Length; i++)
                            {
                                bytBuffer[i] = 0;
                            }
                            int nLen = cliSocket.Receive(bytBuffer);
                            if (nLen > 0)
                            {
                                strRecvMessage.AppendLine(System.Text.Encoding.ASCII.GetString(bytBuffer));//将接收的数据转换成字符串
                                int sLen = 0;
                                while (sLen < nLen)
                                {
                                    RaiseNotifyEvent(NotifyCommand.RecvData, strRecvMessage.ToString().Trim().TrimEnd('\0'));
                                    sLen = nLen + 13;
                                    Thread.Sleep(500);
                                }
                                strRecvMessage.Remove(0, strRecvMessage.Length);
                            }
                            else
                            {
                                //连接断开
                                Close();
                                RaiseNotifyEvent(NotifyCommand.Break, " 接收到的报文数据长度为0！");
                                break;
                            }
                        }
                    }
                }
                catch (SocketException ex)
                {
                    Close();
                    RaiseNotifyEvent(NotifyCommand.Break, "与DTS连接中断！" + ex.Message);
                }
                Thread.Sleep(150);
            }
        }

        private void RaiseNotifyEvent(NotifyCommand Command, object oState)
        {
            if (this.Notify != null)
            {
                Notify(Command, oState);
            }
        }
    }
}
